import React, { Component } from 'react'
import { Redirect } from "react-router-dom"
import { Form, Input, Button, message } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import http from "../../api/index"
import "./login.css"

export default class Login extends Component {
  onFinish = async (values) => {
    // 请求登录接口
    const value = await http.post('/login', values)
    const { data } = value
    // 登录状态提醒
    message[data.state](data.message)
    // 有 token 表示登录成功，跳转首页路由
    if (data.token) {
      // 浏览器保存 token
      localStorage.setItem('grain_token', data.token)
      localStorage.setItem('grain_name', data.name)
      this.props.history.push('/admin')
    }
  }
  render() {
    // 如果本地有用户信息就直接跳转到首页
    let token = localStorage.getItem('grain_token')
    if (token) {
      return <Redirect to="/admin"></Redirect>
    }
    return (
      <div className="login">
        <header className="login-header">
          <h1>React后台管理系统</h1>
        </header>
        <div className="login-content">
          <h2>用户登录</h2>
          <Form
            name="normal_login"
            className="login-form"
            onFinish={this.onFinish}
          >
            <Form.Item
              name="username"
              initialValue="admin"
              rules={[
                { required: true, whitespace: true, message: '账号必须输入' },
                { min: 3, message: '账号长度不能小于3位' },
                { max: 8, message: '账号长度不能大于8位' },
                { pattern: /^[A-Za-z_\d]+$/, message: '只能包含数字、字母、下划线' },
              ]}
            >
              <Input
                prefix={<UserOutlined className="site-form-item-icon" />}
                type="text"
              />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  pattern: /^[A-Za-z\d]{6,12}$/,
                  message: '密码长度在6~18之间,只能包含数字、字母!',
                },
              ]}
            >
              <Input
                prefix={<LockOutlined className="site-form-item-icon" />}
                type="password"
                placeholder="密码"
              />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" className="login-form-button">
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    )
  }
}
